require 'net/http'
require 'net/https'
require 'uri'

module Provider

  class SunriseCH< AbstractProvider

    @sms_sender

    @login_name
    @password
    
    def initialize(sms_sender)
      @sms_sender = sms_sender
      @login_name = @sms_sender.get_main.login_name
      @password = @sms_sender.get_main.password
    end

    def send(to, text)

      #SmsWidget::Main.logger.debug "login = #{login}\npassword = #{password}\nto = #{to}\ntext = #{text}\nuse_ssl = #{use_ssl}"

      # URLs
      referer_url = 'http://www.sunrise.ch/'
      login_url = 'http://mip.sunrise.ch/mip/dyn/login/login?SAMLRequest=fVJLT8MwDL4j8R%2Bi3PsaQqBoLRogxCQe1dZx4Ja23hrW2iVON%2Fj3dB0T4wDHOJ%2B%2Fh%2B3x1UdTiw1YNoSxjPxQCsCCSoOrWC6yO%2B9SXiWnJ2PWTd2qSecqnMF7B%2BxE34msho9YdhYVaTasUDfAyhVqPnl8UCM%2FVK0lRwXVUkxvY4lr0%2BZ5uXwDRLOuqoZyXKOharkCg3n7ttZUEpEULwdbo52tKXMHU2Sn0fWlMLz0wnNvdJFFkTo%2FU%2BHoVYr0W%2Bna4D7Bf7byPYjVfZalXvo8zwaCjSnBPvXoWK6IVjX4BTVSTJjBut7ODSF3Ddg52I0pYDF7iGXlXMsqCLbbrf%2FTFOiAO7SG%2B1cV6IJ3IVLNbDY9ubMdyGQYrBqy2aOJ%2Fu9cH7zI5EdtHBxRJd8L2%2BWY3qZUm%2BJTTOqatjcWtDvIizuyjXZ%2Fq0V%2BNFRM6S0HqOqQWyjM0kApRZDsVX9fRn8vXw%3D%3D'
      send_url = 'http://mip.sunrise.ch/mip/dyn/sms/sms?.lang=de'

      # Settings
      user_agent = "Sunrise SMS Widget"
      cookie = ''
      port = 80

      # Now do the login
      login_uri = URI.parse(login_url)

      http = Net::HTTP.new(login_uri.host, port)
      post_data = "username=#{@login_name}&password=#{@password}"
      post_headers = { 'Referer' => referer_url, 'Cookie' => cookie, 'Content-Type' => 'application/x-www-form-urlencoded'}

      resp, data = http.post(login_uri.path, post_data, post_headers)
      resp.each { |key, val|
      if key == 'set-cookie'
          cookie = val
          SmsWidget::Main.logger.info 'accepted cookie: ' + val
      end
      }
      SmsWidget::Main.logger.debug resp
      SmsWidget::Main.logger.debug data
      
      # Now we can send the message
      send_uri = URI.parse(send_url)

      http = Net::HTTP.new(send_uri.host, port)
      post_data = "task=send&recipient=#{to}&message=#{text}"
      post_headers = { 'Referer' =>  login_url, 'Cookie' => cookie, 'Content-Type' => 'application/x-www-form-urlencoded'}

      sent=false

      resp, data = http.post(send_uri.path, post_data, post_headers)
      data.each { |line|
        if line =~ /successOutput/
          sms_sent()
          sent=true
        end
      }
        unless sent
          sms_not_sent('test')
        end
     end

    def sms_sent()
      @sms_sender.sms_sent
    end
    
    def sms_not_sent(reason)
      @sms_sender.sms_not_sent(reason)
    end
  end
    
end
